/**
 * Created by Administrator on 2017/3/21.
 */
import React, {Component, Fragment} from 'react';
import {
  Form,
  Button,
  Badge,
  Radio,
  Tooltip,
  DatePicker,
  Descriptions,
  Tag,
  Icon,
  Switch,
  message,
  Modal,
  Drawer, Carousel, Input,Select
} from 'antd';
import {connect} from 'dva';
import forEach from 'lodash/forEach';
import request from '@/utils/request';
import {
  getTimeDistance,
  renderValveOpen,
  download,
  formateObjToParamStr,
  renderSignalIntensity,
  afterCloseModal
} from '@/utils/utils';
import moment from 'moment';
import ReactDataGrid from 'react-data-grid';
import Order from './Order'
import MyPagination from "@/components/MyPagination";
import Loading from "@/components/Loading";

const {confirm} = Modal;
const {Option} = Select;
const ButtonGroup = Button.Group;
const FormItem = Form.Item;
class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      detail: {
        concentrator_info:{},
        latest_data:[],
        config:{}
      },
      searchParams:{
        page: 1,
        per_page: 50,
        command_code:'',
        status:''
      },
      meta: {total: 0, per_page: 50,current_page:1},
      editRecord: {},
      data:[],
      loading:false

    };
  }

  componentDidMount() {
    // console.log('this', this.props.editRecord);
    const that = this;
    that.handleSearch(this.state.searchParams);
  }

  renderSimpleForm() {
    const searchParams =this.state.searchParams
    const getFieldDecorator=this.props.form.getFieldDecorator
    return (
      <Form layout="inline" className="search-form">
        <FormItem label={'指令特征码'}>
          {getFieldDecorator('command_code', {
            initialValue: '',
          })(
            <Input style={{width:'120px'}}></Input>
          )}
        </FormItem>
        <FormItem label={'状态'}>
          {getFieldDecorator('status', {
            initialValue: '',
          })(
           <Select style={{width:'120px'}}>
             <Option value={''}>全部</Option>
             <Option value={'-1'}>下发失败</Option>
             <Option value={'1'}>下发中</Option>
             <Option value={'2'}>下发成功</Option>
           </Select>
          )}
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  ...fieldsValue,
                  page: 1,
                  per_page: searchParams.per_page,
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
          <Button style={{ marginLeft: 8 }} type={'primary'} className={'green-btn'} icon='cloud-download' onClick={()=>{
            this.setState({
              OrderModal:true
            })
          }}>
            下发指令
          </Button>
        </FormItem>

      </Form>
    );
  }
  handleSearch=(searchParams)=>{
    const that = this;
    this.setState({
      loading:true
    })
    request(`/command_logs`, {
      method: 'GET',
      params: {...searchParams,number:this.props.editRecord.number,order_direction:'desc'}
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          data: response.data.data,
          meta:response.data.meta,
          loading:false
        });
      }

    });
  }
  handleFormReset=()=>{
    this.handleSearch({
      page: 1,
      per_page: 50,
      command_code:'',
      status:''
    })
  }

  render() {
    const defaultColumnProperties = {
      resizable: true,
    };
    const that=this
    const {detail, searchParams,meta,data,loading} = this.state;
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          const {
            meta
          } = this.state;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name: '创建时间',
        width: 170,
        key: 'created_at',
      },
      {
        name: '操作人',
        width: 150,
        key: 'operator_name',
      },
     {
        name: '状态',
        width: 100,
        key: 'status',
        formatter: (event) => {
          if (event.value === -1) {
            return '下发失败'
          } else if (event.value === 1) {
            return '下发中'
          } else if (event.value === 2) {
            return '下发成功'
          }
        }
      },
      {
        name: '指令内容',
        width: 460,
        key: 'command',
        formatter: (event) => {
          return <Tooltip placement="topLeft" title={event.value}><span>{event.value}</span></Tooltip>
        },
      },
      {
        name: '指令特征码',
        width: 140,
        key: 'command_code',
        formatter: (event) => {
          if(event.value==='82'){
            return `${event.value}(阀控)`
          }else if(event.value==='E0'){
            return `${event.value}(请求上线)`
          }else if(event.value==='E4'){
            return `${event.value}(读电压电流)`
          }else if(event.value==='E5'){
            return `${event.value}(读地址)`
          }else if(event.value==='E7'){
            return `${event.value}(读上报情况)`
          }else if(event.value==='83'){
            return `${event.value}(设置上报参数)`
          }else if(event.value==='85'){
            return `${event.value}(设置表底数)`
          }else if(event.value==='84'){
            return `${event.value}(设置服务器地址)`
          }else if(event.value==='EC'){
            return `${event.value}(设置出厂)`
          }else if(event.value==='ED'){
            return `${event.value}(取消出厂)`
          }else if(event.value==='EE'){
            return `${event.value}(请求自测试)`
          }else if(event.value==='E8'){
            return `${event.value}(读点冻结)`
          }else if(event.value==='E9'){
            return `${event.value}(读日冻结)`
          }else if(event.value==='E2'){
            return `${event.value}(校时)`
          }else if(event.value==='E3'){
            return `${event.value}(调整端口号)`
          }else if(event.value==='EA'){
            return `${event.value}(读参数)`
          }else if(event.value==='EB'){
            return `${event.value}(读表数据)`
          }else if(event.value==='EF'){
            return `${event.value}(读自测结果)`
          }else if(event.value==='F0'){
            return `${event.value}(读事件记录)`
          }else if(event.value==='86'){
            return `${event.value}(充值)`
          }else if(event.value==='E6'){
            return `${event.value}(清零)`
          }else{
            return `${event.value}`
          }
        },
      },
      {
        name: '状态码',
        width: 100,
        key: 'status_code',
      },
      {
        name: '执行结果',
        width: 720,
        key: 'result',
        formatter: (event) => {
          return <Tooltip placement="topLeft" title={JSON.stringify(event.value)}><span>{JSON.stringify(event.value)}</span></Tooltip>
        },
      },

  /*    {
        name: '操作',
        width: 80,
        key: 'right',
        classname: 'operate',
        formatter: (event) => {
          const {detail, ownerDetail} = this.state;
          // console.log('detail',detail)
          let meter_config = detail.config.meter_config;
          if(meter_config && meter_config['port' + event.row.index]){
            return  <Fragment>
              <Button
                className={'btn-cyan'}
                type="primary"
                icon="eye"
                size="small"
                onClick={(e) => {
                }
                }
              >详情
              </Button>
            </Fragment>
          }else{
            return ''
          }

        }
      }*/
    ].map(c => ({...defaultColumnProperties, ...c}));
    const reverceData = detail.latest_data;
    return (
      <div>
        <div className="table-condition">{this.renderSimpleForm()}</div>

        <div style={{ marginTop: '10px'}}>
          <div className={'table-data-content'}>
            <ReactDataGrid
                columns={columns}
                rowGetter={i => {
                  return { ...data[i], _index: i };
                }}
                rowsCount={data.length}

                minHeight={'calc(100vh - 180px)'}
              />
            {
              loading && <Loading/>
            }
          </div>

        </div>
        <div className="table-pagination" style={{marginTop:'10px'}}>
          <MyPagination searchCondition={{ ...searchParams }}
                        meta={meta} handleSearch={this.handleSearch}/>
        </div>

        <Drawer
          title={`${this.props.editRecord.number} 下发指令`}
          placement="right"
          onClose={() => {
            this.setState({
              OrderModal: false,
              editRecord: {},
            });
          }}

          width={500}
          visible={this.state.OrderModal}
        >
          <Order  handleSearch={this.handleSearch} searchCondition={{ ...searchParams }}  editRecord={this.props.editRecord} id={this.props.editRecord.id}></Order>
        </Drawer>
      </div>
    );
  }
}

const AddPoliciesFormWrap = Form.create()(AddPoliciesForm);
export default connect()(AddPoliciesFormWrap);
